package com.cti.ftpservice.vo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

import com.cti.ftpservice.ftp.FTPDownFiles;
import com.cti.ftpservice.ftp.FTPUploadFiles;
import com.cti.ftpservice.ftp.FileUtils;
import com.cti.ftpservice.utils.FtpWsManagerUtil;
import com.ctibook.booksystem.ws.FtpFileUploadInfoViewVo;


/**
 * ftp服务器类
 * 
 * @author lj
 *
 */
public class FtpServiceDownloadInfoVo extends FtpDownLoadBaseServiceInfoVo{
	/**
	 * ftp类型   
	 * ftp_uploadFile：将其他ftp的文件推送到本ftp
	 * ftp_downloadFile:从本ftp下载文件
	 */
	

	/**
	 * 开始
	 * @throws InterruptedException
	 * @throws NumberFormatException
	 * @throws IOException
	 */
	public void startDownLoadFiles() throws InterruptedException, NumberFormatException,
			IOException {
		setStop(false);
		for (int i = 1; i <= getThreadCount(); i++) {
			FTPDownFiles ftpDownFiles = new FTPDownFiles(this);
			Thread thread = new Thread(ftpDownFiles);
			thread.setName("downloadThread" + i);
			thread.start();
		}
	}

	
	public void startUpLoadFiles(){
		setStop(false);
		for (int i = 1; i <= getThreadCount(); i++) {
			FTPUploadFiles ftpUpFiles = new FTPUploadFiles(this);
			Thread thread = new Thread(ftpUpFiles);
			thread.setName("downloadThread" + i);
			thread.start();
		}
	}
	

	
	/**
	 * 下载文件完成
	 */
	public void stopDownLoadFiles() {
		try {
			synchronized (this) {
				setFinished(true);
				setStop(true);
			}
			FileUtils.saveDownLoadFileInfoToDB(id,dealFiles,this.ftpServiceType);
			dealFiles.clear();
		} catch (Exception e) {
			
		}
	}
	
	/**
	 * 上传文件完成
	 */
	public void stopUpLoadFiles(){
		try {
			synchronized (this) {
				setFinished(true);
				setStop(true);
			}
			//保存数据库记录
			for (FtpFileUploadInfoViewVo ftpFileInfo : uploadDealFiles) {
				FtpWsManagerUtil.addUploadFtpFileRecord(ftpFileInfo,getId());
				List<String> uploadrecordIds=FtpWsManagerUtil.getFtpFileMatchFtpServiceRecordIdsByFtpFileIdAndFtpServiceId(ftpFileInfo.getId(),getId());
				for (String uploadrecordId : uploadrecordIds) {
					FtpWsManagerUtil.updateFtpFileMatchFtpServiceRecordPassInfo(uploadrecordId,true);
				}
			}
			uploadDealFiles.clear();
		} catch (Exception e) {
			
		}
	}
	
	public void finish(){
		try {
			synchronized (this) {
				setFinished(true);
				setStop(true);
			}
			FileUtils.writeDownLoadFilePaths(id,dealFiles);
			dealFiles.clear();
		} catch (Exception e) {
			
		}
	}
	
}
